package com.yuyang.wifi.utils;

import android.os.Build;
import android.text.TextUtils;

import com.yuyang.wifi.constant.AppConstant;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import androidx.annotation.RequiresApi;

/**
 * 日期的一个工具类
 */

public class DatePickerUtil {

    public static final int[] months = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};


    private static boolean isLeafYear(int year) {
        return year % 400 == 0 || year / 4 == 0 && year / 100 != 0;
    }

    public static int getDaysOfMonth(int year, int month) {

        if (month == months[0] || month == months[2] || month == months[4] || month == months[6] ||
                month == months[7] || month == months[9] || month == months[11])
            return 31;
        else if (month == months[3] || month == months[5] || month == months[8] || month == months[10])
            return 30;

        if (isLeafYear(year)) return 29;
        return 28;
    }

    public static int getCurrentYear() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    public static int getCurrentMonth() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MONTH) + 1;
    }

    public static int getCurrentDay() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    public static int getCurrentHouse() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.HOUR_OF_DAY);
    }

    public static int getCurrentMinute() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MINUTE);
    }

    public static int getCurrentSecond() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.SECOND);
    }

    public static int getStatus(long time) {
        long seconds = time / 1000; //秒
        if (seconds < 5 * 60) {
            return 1;
        } else if (seconds >= 5 * 60 && seconds <= 30 * 60) {
            return 2;
        } else if (seconds > 30 * 60) {
            return 3;
        }
        return 0;
    }

    /**
     * 得到 时间间隔字符串
     *
     * @param time long类型
     * @return
     */
    public static String getLongFormatTime(long time) {
        int status = getStatus(time);
        if (status == 1) {
            return "5分钟以内";
        } else if (status == 2) {
            return "5-30分钟";
        } else if (status == 3) {
            return "30分钟以上";
        }
        return "";
    }

    /**
     * 设置年月日
     *
     * @param calendar
     * @param year
     * @param month
     * @param date
     */
    public static void setDate(Calendar calendar, int year, int month, int date) {
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DATE, date);
    }

    /**
     * 设置开始时间
     *
     * @param calendar
     */
    public static void setStartTime(Calendar calendar) {
        int hrs = 0;
        int min = 0;
        int sec = 0;
        calendar.set(Calendar.HOUR_OF_DAY, hrs);
        calendar.set(Calendar.MINUTE, min);
        calendar.set(Calendar.SECOND, sec);
    }

    /**
     * 设置结束时间
     *
     * @param calendar
     */
    public static void setEndTime(Calendar calendar) {
        int hrs = 23;
        int min = 59;
        int sec = 59;
        calendar.set(Calendar.HOUR_OF_DAY, hrs);
        calendar.set(Calendar.MINUTE, min);
        calendar.set(Calendar.SECOND, sec);
    }

    /**
     * 得到秒级时间
     *
     * @param calendar
     * @return
     */
    public static long getUnixTimeInMillis(Calendar calendar) {
        long millisTime = calendar.getTimeInMillis() / 1000;
        return millisTime;
    }


    //得到当前时间
    public static String getNowTimeStamp() {
        long time = System.currentTimeMillis();
        String nowTimeStamp = String.valueOf(time / 1000);
        return nowTimeStamp;
    }

    /**
     * @param amount amount 今日+0; 明日+1; 未来3日 +3;未来7日 +7 看需求
     * @return 开始时间
     */
    public static long getStartTime(int amount) {
        Calendar calendar = Calendar.getInstance();
        //设置日期
        DatePickerUtil.setDate(calendar, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        calendar.add(Calendar.DAY_OF_YEAR, +amount);
        //设置开始时间
        DatePickerUtil.setStartTime(calendar);
        long startTime = DatePickerUtil.getUnixTimeInMillis(calendar);
        return startTime;
    }

    /**
     * @param amount amount 今日+0; 明日+1; 未来3日 +3;未来7日 +7 看需求
     * @return 结束时间
     */
    public static long getEndTime(int amount) {
        Calendar calendar = Calendar.getInstance();
        //设置日期
        DatePickerUtil.setDate(calendar, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        calendar.add(Calendar.DAY_OF_YEAR, +amount);
        //设置结束时间
        DatePickerUtil.setEndTime(calendar);
        long endTime = DatePickerUtil.getUnixTimeInMillis(calendar);
        return endTime;
    }

    /**
     * 得到未来的开始时间 比如2017年3月3日~2017年10月30日
     *
     * @param year  2017
     * @param month 3
     * @param day   3
     * @return
     */
    public static long getFutureStartTime(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        //设置日期
        DatePickerUtil.setDate(calendar, year, month, day);
        //设置开始时间
        DatePickerUtil.setStartTime(calendar);
        long startTime = DatePickerUtil.getUnixTimeInMillis(calendar);
        return startTime;
    }

    /**
     * 得到未来的结束时间 比如2017年3月3日~2017年10月30日
     *
     * @param year  2017
     * @param month 10
     * @param day   30
     * @return
     */
    public static long getFutureEndTime(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        //设置日期
        DatePickerUtil.setDate(calendar, year, month, day);
        //设置开始时间
        DatePickerUtil.setEndTime(calendar);
        long startTime = DatePickerUtil.getUnixTimeInMillis(calendar);
        return startTime;
    }

    /**
     * @param timeInMillis 传入的时间
     * @param format       时间的格式
     * @return 根据格式得到日期
     */
    public static String getStringFormatDate(Long timeInMillis, String format) {
        if (timeInMillis == null) {
            timeInMillis = 0l;
        }
        if (timeInMillis >= DatePickerUtil.getStartTime(0)
                && timeInMillis <= DatePickerUtil.getEndTime(0)) {

            return "今天";
        } else if (timeInMillis >= DatePickerUtil.getStartTime(-1)
                && timeInMillis <= DatePickerUtil.getEndTime(-1)) {

            return "昨天";
        }
        return getFormatDate(timeInMillis, format);
    }

    /**
     * @param timeInMillis 传入的时间
     * @param format       时间的格式
     * @return 根据时间格式的时间
     */
    public static String getFormatDate(Long timeInMillis, String format) {
        if (timeInMillis == null) {
            timeInMillis = 0l;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(new Date(timeInMillis));
    }

    public static String getFormatDate1(Long timeInMillis, String format) {
        if (timeInMillis == null) {
            timeInMillis = 0l;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(new Date(timeInMillis));
    }

    //得到时间间隔
    public static String getTimeDistance(Long timeInMillis) {

        if (timeInMillis == null) return "";
        int days = (int) (timeInMillis / (60 * 60 * 24));//得到总的天数

        int year = days / 365;
        int month = (days - year * 365) / 30;
        int day = days - year * 365 - month * 30;

        StringBuilder timeBuilder = new StringBuilder();

        if (year > 0) {
            timeBuilder.append(year).append("年");
        }

        if (month > 0) {
            timeBuilder.append(month).append("月");
        }
        timeBuilder.append(day).append("天");

        return timeBuilder.toString();

    }


    //Java将Unix时间戳转换成指定格式日期
    public static String stampToDate(String timestampString) {
        Long timestamp = Long.parseLong(timestampString) * 1000;
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp));
        return date;
    }


    //Java将Unix时间戳转换成指定格式日期 接收毫秒级时间戳  "yyyy-MM-dd HH:mm:ss"
    public static String stampToWantDate(Long timestampString, String format) {
        String date = new SimpleDateFormat(format).format(new Date(timestampString));
        return date;
    }

    /**
     * 获得指定日期的后一天
     * <p>
     * 如2017-11-29转化为2017-11-30
     *
     * @param time   long类型的秒级时间戳
     * @param format "2017-11-29"
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public static String getSpecifiedDayAfter(Long time, String format) {

        String specifiedDay = getFormatDate(time, format);
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yy.MM.dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day + 1);

        String dayAfter = new SimpleDateFormat("yyyy.MM.dd").format(c.getTime());
        return dayAfter;
    }


    /**
     * 日期转星期
     *
     * @param datetime
     * @return
     */
    public static String getBelongWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 两个日期相差小时数
     *
     * @param
     * @return
     */
    public static String getHouseNum(String startDate, String endDate) {

        Long startTimestamp = getStrToTimestamp(startDate);
        Long endTimestamp = getStrToTimestamp(endDate);

        Long timestamp = endTimestamp - startTimestamp;
        double hours = (double) (timestamp / (60 * 60.0));
        //利用BigDecimal来实现四舍五入.保留一位小数
        double result = new BigDecimal(hours).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
        return String.valueOf(result);
    }


    public static Long getStrToTimestamp(String str) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = new Date();
        try {
            date1 = simpleDateFormat.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long timestamp = date1.getTime() / 1000;
        return timestamp;
    }


    /**
     * 毫秒转日时分秒
     *
     * @param
     * @return
     */
    public static String formatDuring(long mss) {
        long days = mss / (1000 * 60 * 60 * 24);
        long hours = (mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (mss % (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (mss % (1000 * 60)) / 1000;
        return days + " days " + hours + " hours " + minutes + " minutes "
                + seconds + " seconds ";

    }

    /**
     * 获取当前时间戳
     *
     * @param
     * @return
     */
    public static Long getCurrentTimestap() {
        //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String currentTime = simpleDateFormat.format(curDate);
        Long time = getStrToTimestamp(currentTime);
        return time;
    }

    /**
     * 获取当前时间戳
     *
     * @param
     * @return
     */
    public static Long getSpacerDay() {
        //获取当前时间
        Long day = null;
        try {
            String registerTime = SpUtil.find(AppConstant.KEY_REGISTER_TIME);
            if (TextUtils.isEmpty(registerTime)) {
                Long currentTimestap = getCurrentTimestap();
                String registerTimes = String.valueOf(currentTimestap);
                SpUtil.saveOrUpdate(AppConstant.KEY_REGISTER_TIME, registerTimes);
            }
            Long currentTimestap = getCurrentTimestap();
            day = (Long.valueOf(currentTimestap) - Long.valueOf(registerTime)) / 86400;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return day + 1;
    }

    public static boolean isToday() {

        String oldDate = SpUtil.find(AppConstant.KEY_TODAY);//获取保存的日期
        //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd");
        Date curDate = new Date(System.currentTimeMillis());
        String currentTime = simpleDateFormat.format(curDate);

        if (!TextUtils.isEmpty(oldDate) && currentTime.equals(oldDate)) {
            return false;
        } else {
            SpUtil.saveOrUpdate(AppConstant.KEY_TODAY, currentTime);
        }
        return true;
    }

    public static boolean isTodayWithdrawFirst() {

        String oldDate = SpUtil.find(AppConstant.KEY_TODAY_WITHDRAW);//获取保存的日期
        //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd");
        Date curDate = new Date(System.currentTimeMillis());
        String currentTime = simpleDateFormat.format(curDate);

        if (!TextUtils.isEmpty(oldDate) && currentTime.equals(oldDate)) {
            return false;
        } else {
            SpUtil.saveOrUpdate(AppConstant.KEY_TODAY_WITHDRAW, currentTime);
        }
        return true;
    }

    public static boolean isHomeFirst() {

        String oldDate = SpUtil.find(AppConstant.KEY_HOME_FIRST);//获取保存的日期
        //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd");
        Date curDate = new Date(System.currentTimeMillis());
        String currentTime = simpleDateFormat.format(curDate);

        if (!TextUtils.isEmpty(oldDate) && currentTime.equals(oldDate)) {
            return true;
        } else {
            SpUtil.saveOrUpdate(AppConstant.KEY_HOME_FIRST, currentTime);
        }
        return false;
    }


    public static Long getFlutterDate(int num, int hours, int minutes, int seconds) {
        Date date = new Date();
        date.setDate(date.getDate() + num);
        date.setHours(hours);
        date.setMinutes(minutes);
        date.setSeconds(seconds);
        Long goodsTime = date.getTime();
        return goodsTime;
    }

}
